﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using JetBrains.Annotations;
using Newtonsoft.Json.Linq;

namespace SimpleCmsWithAbp.Helper
{
    public static class ExtJs
    {
        public static readonly string SortFormatString = "{0} {1}";

        public static string OrderBy([NotNull] string sortStr, [NotNull] JObject allowSorts)
        {
            var first = allowSorts.Properties().FirstOrDefault();
            if (first == null || string.IsNullOrEmpty((string)first.Value)) throw new Exception("noAllowSortDefine");
            var defaultSort = string.Format(SortFormatString, first.Value, "");
            var sortObject = JArray.Parse(sortStr);
            var q = from p in sortObject
                    let name = (string)p["property"]
                let dir = (string)p["direction"] == "ASC" ? "ASC" : "DESC"
                from KeyValuePair<string, JToken> property in allowSorts
                let submitName = property.Key
                where name.Equals(submitName)
                select string.Format(SortFormatString, property.Value, dir);
            var sorter = string.Join(",", q);
            return string.IsNullOrEmpty(sorter) ? defaultSort : sorter;
        }

    }
}